//
//  WJPurchaseDiscountViewController.swift
//  PDFSign
//
//  Created by 李永彬 on 2025/10/21.
//

import UIKit
import StoreKit

class WJPurchaseDiscountViewController: UIViewController {
    
    private var products: [SKProduct] = [] {
        didSet {
            setDisplayProducts()
        }
    }
    
    var dimissAction:(() -> Void)?
    var yearProduct: SKProduct? = nil
    var yearProductDiscount: SKProduct? = nil
    
    private lazy var continueButton: UIButton = {
        let button = UIButton(type: .system)
        button.setTitle("Continue", for: .normal)
        button.backgroundColor = UIColor(hex: "#1F87F6")
        if let backgroundImage = UIImage(named: "button_layer") {
            let capInsets = UIEdgeInsets(top: 0, left: 32, bottom: 0, right: 32)
            let resizableImage = backgroundImage.resizableImage(withCapInsets: capInsets, resizingMode: .stretch)
            button.setBackgroundImage(resizableImage, for: .normal)
        }
        button.setTitleColor(UIColor(hex: "#FFFFFF"), for: .normal)
        button.titleLabel?.font = UIFont.montserratMedium(20)
        button.layer.cornerRadius = 32
        button.layer.masksToBounds = true
        button.addTarget(self, action: #selector(continueButtonTapped), for: .touchUpInside)
        return button
    }()
    
    lazy var titleImgView: UIImageView = {
        let imgView = UIImageView()
        imgView.image = UIImage(named: "purchase_title")
        imgView.contentMode = .scaleAspectFit
        imgView.alpha = 1.0
        return imgView
    }()
    
    lazy var iconImgView: UIImageView = {
        let imgView = UIImageView()
        imgView.image = UIImage(named: "purchase_icon")
        imgView.contentMode = .scaleAspectFit
        // 设置锚点为底部中心，这样旋转时底部保持不动
        imgView.layer.anchorPoint = CGPoint(x: 0.5, y: 1.0)
        return imgView
    }()
    
    private lazy var descriptionLabel: UILabel = {
        let label = UILabel()
        label.text = "This subscription gives you unlimited access to all features. Your subscription will automatically renew. By continuing you accept Routine your Terms of Service & Privacy Policy."
        label.textColor = UIColor(hex: "#FFFFFF", alpha: 0.4)
        label.numberOfLines = 0
        label.font = UIFont.montserratRegular(10)
        label.textAlignment = .center
        return label
    }()
    
    private lazy var trialLabel: UILabel = {
        let label = UILabel()
        label.textColor = UIColor(hex: "#FFFFFF", alpha: 0.8)
        label.numberOfLines = 0
        label.font = UIFont.montserratSemiBold(24)
        label.textAlignment = .center
        return label
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = UIColor(hex: "#08121F")
        setupNavigationBar()
        WJPurchaseManager.shared.delegate = self
        commonInitSubViews()
        
        loadProducts()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        // 视图显示后开始跷跷板动画
        startStrongSeesawAnimation()
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        // 视图消失时停止动画
        stopAllAnimations()
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        // 确保锚点设置后重新定位
        adjustIconImageViewPosition()
    }
    
    func loadProducts() {
        WJProgressHUD.showLoading()
        let identifiers: Set<String> = Set(WJSku.allCases.map { $0.rawValue })
        WJPurchaseManager.shared.fetchProducts(identifiers: identifiers)
    }
    
    func setDisplayProducts() {
        // 定义不同情况下的产品ID集合
       for product in products {
           if product.productIdentifier == WJSku.yearly.rawValue {
               yearProduct = product
           }
           
           if product.productIdentifier == WJSku.yearlyDiscount.rawValue {
               yearProductDiscount = product
           }
       }
        
        trialLabel.text = trailString
    }
    
    func commonInitSubViews() {
        view.addSubview(titleImgView)
        view.addSubview(iconImgView)
        view.addSubview(trialLabel)
        view.addSubview(descriptionLabel)
        view.addSubview(continueButton)
        titleImgView.snp.makeConstraints { make in
            make.top.equalTo(view.safeAreaLayoutGuide.snp.top).offset(50)
            make.leading.trailing.equalToSuperview().inset(16)
            make.height.equalTo(100)
        }
       
        iconImgView.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.leading.trailing.equalToSuperview().inset(16)
        }
        
        trialLabel.snp.makeConstraints { make in
            make.bottom.equalTo(continueButton.snp.top).offset(-30)
            make.leading.trailing.equalToSuperview().inset(16)
        }
        
        continueButton.snp.makeConstraints { make in
            make.bottom.equalTo(descriptionLabel.snp.top).offset(-10)
            make.leading.trailing.equalToSuperview().inset(32)
            make.height.equalTo(64)
        }
        
        descriptionLabel.snp.makeConstraints { make in
            make.bottom.equalToSuperview().offset(-safeAreaBottom)
            make.leading.trailing.equalToSuperview().inset(16)
            make.height.equalTo(44)
        }
    }
    
    // MARK: - 动画方法
    
    // 调整 iconImgView 位置以适配锚点变化
    private func adjustIconImageViewPosition() {
        // 由于改变了锚点，需要调整位置来保持视觉上的居中
        let currentFrame = iconImgView.frame
        let newY = currentFrame.origin.y + currentFrame.height / 2
        iconImgView.frame.origin.y = newY
    }

    // 更明显的跷跷板效果
    private func startStrongSeesawAnimation() {
        stopAllAnimations()

        // 给系统一个渲染周期
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.01) {
            let rotationAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
            rotationAnimation.fromValue = -0.08  // 从当前值开始
            rotationAnimation.toValue = 0.18     // 向右倾斜
            rotationAnimation.duration = 1.5
            rotationAnimation.autoreverses = true
            rotationAnimation.repeatCount = .infinity
            rotationAnimation.timingFunction = CAMediaTimingFunction(name: .linear)
            rotationAnimation.isRemovedOnCompletion = false // 动画完成后不移除
            rotationAnimation.fillMode = .forwards // 保持最后状态
            
            self.iconImgView.layer.add(rotationAnimation, forKey: "strongSeesawAnimation")
            
            let opacityAnimation = CABasicAnimation(keyPath: "opacity")
            opacityAnimation.fromValue = 1.0
            opacityAnimation.toValue = 0.4
            opacityAnimation.duration = 1.5
            opacityAnimation.autoreverses = true
            opacityAnimation.repeatCount = .infinity
            opacityAnimation.timingFunction = CAMediaTimingFunction(name: .linear)
            opacityAnimation.isRemovedOnCompletion = false
            opacityAnimation.fillMode = .forwards
            
            self.titleImgView.layer.add(opacityAnimation, forKey: "opacityAnimation")
        }
    }
    
    // 停止所有动画
    private func stopAllAnimations() {
        iconImgView.layer.removeAllAnimations()
        titleImgView.layer.removeAllAnimations()
        
        // 恢复初始状态
        titleImgView.alpha = 1.0
        iconImgView.layer.transform = CATransform3DIdentity
    }

    private func setupNavigationBar() {
        // 左侧关闭按钮
        let leftBar = UIBarButtonItem(
            image: UIImage(named: "Icon_line_close")?.withRenderingMode(.alwaysTemplate),
            style: .plain,
            target: self,
            action: #selector(clickLeftBarItemAction(_:))
        )
        leftBar.tintColor = .white
        navigationItem.leftBarButtonItem = leftBar
        
        // 右侧 "Restore" 按钮
        let rightBtn = UIButton(type: .custom)
        rightBtn.setTitle("Restore", for: .normal)
        rightBtn.setTitleColor(.white, for: .normal)
        rightBtn.titleLabel?.font = UIFont.systemFont(ofSize: 12)
        rightBtn.layer.cornerRadius = 16
        rightBtn.layer.borderColor = UIColor(hex: "#FFFFFF").withAlphaComponent(0.6).cgColor
        rightBtn.layer.borderWidth = 1
        rightBtn.addTarget(self, action: #selector(restoreButtonTapped(_:)), for: .touchUpInside)
        rightBtn.frame = CGRect(x: 0, y: 0, width: 60, height: 32)
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightBtn)
    }

    @objc func clickLeftBarItemAction(_ item: UIBarButtonItem) {
        dimissAction?()
        dismiss(animated: true) { [weak self] in
            guard let self = self else { return }
            dimissAction?()
        }
    }
    
    @objc func continueButtonTapped(_ item: UIBarButtonItem) {
        WJProgressHUD.showLoading()
        guard let selectedProduct = yearProductDiscount else {
            WJProgressHUD.showInfo(with: "failed")
            return
        }
        WJPurchaseManager.shared.purchaseProduct(selectedProduct)
    }
    
    @objc func restoreButtonTapped(_ button: UIButton) {
        WJProgressHUD.showLoading()
        WJPurchaseManager.shared.restorePurchases()
    }
    
    var yearProductPrice: String? {
        
        guard let product = yearProduct else { return nil }
        
        // 使用 NumberFormatter 格式化价格
        let numberFormatter = NumberFormatter()
        numberFormatter.numberStyle = .currency
        numberFormatter.locale = product.priceLocale
        
        if let formattedPrice = numberFormatter.string(from: product.price) {
            // 根据订阅周期添加后缀
            let productId = product.productIdentifier.lowercased()
            if productId.contains("yearly") || productId.contains("annual") {
                return "\(formattedPrice)/year"
            } else if productId.contains("monthly") || productId.contains("month") {
                return "\(formattedPrice)/month"
            } else if productId.contains("weekly") || productId.contains("week") {
                return "\(formattedPrice)/week"
            }
            return formattedPrice
        }
        
        return "\(product.price) \(product.priceLocale.currencySymbol ?? "")"
    }
    
    var trailString: String? {
        return "Only \(monthPrice ?? "")" + "\nTotal \(yearProductDiscountPrice ?? "") (\(yearProductPrice ?? ""))"
    }

    var yearProductDiscountPrice: String? {
        
        guard let product = yearProductDiscount else { return nil }
        
        // 使用 NumberFormatter 格式化价格
        let numberFormatter = NumberFormatter()
        numberFormatter.numberStyle = .currency
        numberFormatter.locale = product.priceLocale
        
        if let formattedPrice = numberFormatter.string(from: product.price) {
            // 根据订阅周期添加后缀
            let productId = product.productIdentifier.lowercased()
            if productId.contains("yearly") || productId.contains("annual") {
                return "\(formattedPrice)/year"
            } else if productId.contains("monthly") || productId.contains("month") {
                return "\(formattedPrice)/month"
            } else if productId.contains("weekly") || productId.contains("week") {
                return "\(formattedPrice)/week"
            }
            return formattedPrice
        }
        
        return "\(product.price) \(product.priceLocale.currencySymbol ?? "")"
    }
    
    var monthPrice: String? {
        guard let product = yearProductDiscount else { return nil }
        
        // 使用 NumberFormatter 格式化价格
        let numberFormatter = NumberFormatter()
        numberFormatter.numberStyle = .currency
        numberFormatter.locale = product.priceLocale
        
        // 计算每月价格（年费 ÷ 12个月）
        let yearlyPrice = product.price.doubleValue
        let monthlyPrice = yearlyPrice / 12.0
        
        if let formattedPrice = numberFormatter.string(from: NSNumber(value: monthlyPrice)) {
            return "\(formattedPrice)/month"
        }
        
        // 格式化失败时的备选方案
        return String(format: "%.2f/month", monthlyPrice)
    }
}

extension WJPurchaseDiscountViewController: WJPurchaseManagerDelegate {
    func productsLoaded(products: [SKProduct]) {
        self.products = products
        WJProgressHUD.dismiss()
    }
    
    func purchaseCompleted(result: WJPurchaseResult) {
        switch result {
        case .success(_):
            WJProgressHUD.showInfo(with: "Purchase successful")
           dismiss(animated: true)
            
        case .failure(let error):
            WJProgressHUD.showInfo(with: error)
            
        case .cancelled:
            WJProgressHUD.showInfo(with: "Purchase Canceled")
        case .restored:
            WJProgressHUD.showInfo(with: "Restore successful")
        case .restoreFailure(let error):
            WJProgressHUD.showInfo(with: error)
        }
    }
    
    func productsRequestFailed(error: String) {
        WJProgressHUD.showInfo(with: error)
    }
}

